package com.maiji.cloud.utils;

import com.google.common.collect.Lists;
import com.maiji.cloud.entities.login.UploadRecord;
import org.dom4j.*;
import org.eclipse.jetty.util.StringUtil;
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;

public class DetailTextUtil {

    public static String dealDetailText(String bucketName, String belongId, String detailsText, List<UploadRecord> uploadRecords) throws Exception {
        if (StringUtil.isBlank(detailsText)) return null;
        Document document = DocumentHelper.parseText("<div>" + detailsText + "</div>");
        List<Map<String, String>> maijiDetailImgs = Lists.newArrayList();
        dealWithElement(bucketName, document.getRootElement(), maijiDetailImgs);
        StringBuilder detailsTextSB = new StringBuilder();
        Iterator iterator = document.getRootElement().elementIterator();
        while (iterator.hasNext()) {
            Element cElement = (Element) iterator.next();
            detailsTextSB.append(cElement.asXML());
        }
        for (Map<String, String> map: maijiDetailImgs) {
            uploadRecords.add(new UploadRecord()
                    .setUuId(UUID_MD5.getUUID())
                    .setBelongId(belongId)
                    .setBucketName(bucketName)
                    .setUploadUserId("admin-1234567890")
                    .setFileName(map.get("fileName"))
                    .setUrl(map.get("url"))
                    .setWidth(Integer.valueOf(map.get("width")))
                    .setHeight(Integer.valueOf(map.get("height")))
                    .setUploadTime(new Date())
                    .setIsMain(0));
        }
        return detailsTextSB.toString();
    }

    public static void dealWithElement(String bucketName, Element element, List<Map<String, String>> maijiDetailImgs) throws Exception {
        Iterator iterator = element.elementIterator();
        while (iterator.hasNext()) {
            Element cElement = (Element) iterator.next();
            List<Element> imgList = cElement.elements("img");
            if (imgList.size() == 0) dealWithElement(bucketName, cElement, maijiDetailImgs);
            else for (Element img: imgList) {
                Attribute src = img.attribute("src");
                String base64Image = src.getValue();
                if (! base64Image.startsWith("data")) continue;
                String belongName = UUID_MD5.getUUID() + "." + base64Image.substring(base64Image.indexOf("/") + 1, base64Image.indexOf(";"));
                base64Image = src.getValue().substring(base64Image.indexOf(",") + 1);
                byte[] detailImgBytes = new BASE64Decoder().decodeBuffer(base64Image);
                ByteArrayInputStream inputStream = new ByteArrayInputStream(detailImgBytes);
                MaijiOSS.aliyunOSSUpload2(bucketName, belongName, inputStream);
                BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(detailImgBytes));
                HashMap<String, String> map = new HashMap<>();
                map.put("url", "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + belongName);
                map.put("width", String.valueOf(bufferedImage.getWidth()));
                map.put("height", String.valueOf(bufferedImage.getHeight()));
                map.put("fileName", belongName);
                maijiDetailImgs.add(map);
                src.setValue("https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + belongName);
                img.setAttributes(Arrays.asList(src));
            }
        }
    }

}
